/*******************************************************************************
 * Copyright 2011 @ Kapil Viren Ahuja
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.kapil.framework.database.impl;

import java.io.BufferedReader;
import java.io.IOException;

import com.kapil.framework.database.IDatabaseSetup;
import com.kapil.framework.logger.ILogger;
import com.kapil.framework.logger.LogFactory;

// TODO: Auto-generated Javadoc
/**
 * The Class MySQLDatabaseSetup.
 */
public class MySQLDatabaseSetup extends AbstractDatabaseSetup implements IDatabaseSetup
{
    
    /** The Constant logger. */
    private static final ILogger logger = LogFactory.getInstance().getLogger(MySQLDatabaseSetup.class);


    /* (non-Javadoc)
     * @see com.kapil.framework.database.AbstractDatabaseSetup#setupDatabase()
     */
    @Override
    public void setupDatabase()
    {
        super.setupDatabase();
    }


    /**
     * Reads a query file line by line and returns in a single string. For MySQL this function will check if a
     * <code>;</code> has been provided in the query and if found it will execute the same there and then assuming it to
     * be the Query delimiter.
     *
     * @param reader the reader
     * @return the string
     */
    @Override
    public String readFile(BufferedReader reader)
    {
        try
        {
            StringBuffer strLine = new StringBuffer();
            String line;

            while ((line = reader.readLine()) != null)
            {
                if (!line.startsWith("--", 0))
                {
                    strLine.append(line);

                    // use ; as the command delimiter and execute the query on the database.
                    if (line.endsWith(";"))
                    {
                        super.exeQuery(strLine.toString());
                        strLine = new StringBuffer();
                    }
                }
            }

            return strLine.toString();
        }
        catch (IOException ioex)
        {
            logger.error("Error reading contents from file.");
            return null;
        }
    }
}
